package com.trio.gamerental.service.impl;

import com.trio.gamerental.dao.UserDao;
import com.trio.gamerental.model.User;
import com.trio.gamerental.pageModel.BaseHelper;
import com.trio.gamerental.pageModel.LoginHelper;
import com.trio.gamerental.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 张俊强~ on 2016/10/26.
 * function:
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public LoginHelper judgeLogin(String loginEmail, String userpsw) {
        Map<String, Object> params = new HashMap<String, Object>();
        LoginHelper loginHelper = new LoginHelper();
        params.put("loginEmail", loginEmail);
        String hql = "from User u where u.loginEmail=:loginEmail";

        User user = userDao.get(hql, params);


        if (user == null) {
            loginHelper.setUser(null);
            loginHelper.setMessage("无此账号");
            loginHelper.setSuccess(false);
        } else if (user.getLoginPsw().equals(userpsw)) {

            loginHelper.setUser(user);
            loginHelper.setMessage("登陆成功");
            loginHelper.setSuccess(true);
        } else {
            loginHelper.setUser(null);
            loginHelper.setMessage("密码错误");
            loginHelper.setSuccess(false);
        }

        return loginHelper;
    }

    @Override
    public BaseHelper judgeEmailExist(String loginEmail) {
        BaseHelper baseHelper = new BaseHelper();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("loginEmail", loginEmail);
        String hql = "from User u where u.loginEmail=:loginEmail";
        User user = userDao.get(hql, params);
        if (user == null) {
            baseHelper.setSuccess(true);
            baseHelper.setMessage("账号可用");
        } else {
            baseHelper.setSuccess(false);
            baseHelper.setMessage("该账号已被占用");
        }
        return baseHelper;
    }

    @Override
    public BaseHelper userRegister(User user) {
        BaseHelper baseHelper = new BaseHelper();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("loginEmail", user.getLoginEmail());
        String hql = "from User u where u.loginEmail=:loginEmail";
        User userTemp = userDao.get(hql, params);
        if (userTemp == null) {
            Serializable id = userDao.save(user);
            if (id == null) {
                baseHelper.setSuccess(false);
                baseHelper.setMessage("注册失败");
            } else {
                baseHelper.setSuccess(true);
                baseHelper.setMessage("注册成功");
            }
        } else {
            baseHelper.setSuccess(false);
            baseHelper.setMessage("账号已被占用");
        }
        return baseHelper;
    }
}
